package com.tkk.monitoring.analyze.exp.sql;

import com.tkk.monitoring.analyze.AnalyzeWorker;
import com.tkk.monitoring.analyze.AnalyzeTarget;
import com.tkk.monitoring.analyze.http.Request;
import io.netty.handler.codec.http.HttpHeaders;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * author: Tkk
 * date: 2015/7/8
 */
public class SQLAnalyzeWorker extends AnalyzeWorker {

    private static Properties properties;

    static {
        try {
            properties = new Properties();
            properties.load(SQLAnalyzeWorker.class.getClassLoader().getResourceAsStream("sql.txt"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public SQLAnalyzeWorker(AnalyzeTarget target) {
        super(target);
    }

    @Override
    public void run() {
        //有请求参数
        if (target.hasParam()) {
            List<String> commands = new LinkedList<String>();
            commands.add("python");
            commands.add(properties.getProperty("exe"));
            commands.add(String.format("-u \"%s\"", Request.toURL(target.getUri(), target.getGetParam())));
            commands.add("--random-agent");
            commands.add("--batch");

            //
            commands.add(String.format("--proxy=\"\"", Request.getProxy(false)));

            //
            if (target.getMethod().equals("post")) {
                commands.add(String.format("--data=\"%s\"", target.getPostBody()));
            }

            //
            HttpHeaders headers = target.getHeaders();
            Iterator<Map.Entry<String, String>> iterator = headers.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                if (StringUtils.equalsIgnoreCase(next.getKey(), "cookie")) {
                    commands.add(String.format("--cookie=\"%s\"", next.getValue()));
                    break;
                }
            }

            //
            String logDoc = properties.getProperty("log");
            File home = new File(logDoc, target.getHost());
            if (!home.exists()) {
                home.mkdir();
            }

            //
            SQLMapWork work = new SQLMapWork();
            work.setCommand(commands);
            work.setTarget(target);
            work.setLogFilePath(String.format("%s\\%s.log", home.getAbsolutePath(), target.getPath().replaceAll("\\.|/", "_"), target.getHost()));
            SQLMapWorker.QUEUE.add(work);
        }
    }
}
